<!-- 编辑弹窗 -->
<template>
   <div class="ele-body">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" >
      <el-card>
        <el-row :gutter="24">
          <el-col :md="8" :sm="24">
            <el-form-item label="客户名称:"  prop="customerId">
              <el-select v-model="form.customerId" filterable clearable placeholder="请选择客户" style="width:100%">
                <el-option v-for="(item, index) in customerDatas" :key="index" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :md="8" :sm="24">
            <el-form-item label="订单日期:">
              <el-date-picker v-model="form.createDate" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="daterange"
                  range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width:100%">
              </el-date-picker>
            </el-form-item>
          </el-col> -->
          <el-col :md="8" :sm="24">
            <el-form-item label="币种:"  prop="currencyId">
              <el-select  filterable clearable v-model="form.currencyId" placeholder="请选择币种" class="ele-fluid" >
                <el-option v-for="(item, index) in currencyDatas" :key="index" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="8" :sm="24">
            <el-form-item label="付款账户:" prop="bankAccountId">
              <el-select v-model="form.bankAccountId" clearable placeholder="请选择付款账户" style="width:100%" >
                <el-option v-for="(item, index) in bankAccountDatas" :key="index" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="8" :sm="24" >
            <el-form-item label="付款日期:" prop="recDate">
              <el-date-picker v-model="form.recDate" type="date" placeholder="请输入付款日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width:100%"/>
            </el-form-item>
          </el-col>
          <!-- <el-col :md="8" :sm="24">
            <el-form-item label="币种:" >
              <el-select v-model="form.currencyId" clearable placeholder="请选择币种" style="width:100%"  @change="changeCurrencyRate">
                <el-option v-for="(item, index) in currencyDatas" :key="index" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :md="8" :sm="24">
            <el-form-item label="汇率:" >
              <el-input v-model="form.rate"    >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :md="8" :sm="24">
            <el-form-item label="付款金额:" prop="payAmount">
              <el-input v-model="form.payAmount" disabled placeholder="请输入付款金额" @change="setAmount"  >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :md="8" :sm="24">
            <el-form-item label="付款金额" label-width="100px" prop="payAmountCn" >
              <el-input v-model="form.payAmountCn"  disabled  prefix-icon="el-icon-_rmb" >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card>
        <div slot="header" class="clearfix" style="display: flex;justify-content:space-between;" >
          <div style="width: 8%;" >出库单列表</div>
          <div style="width: 92%;display: flex;justify-content:start;" >
            <div style="width: 100%;color:var(--color-primary)" > 
              <el-button type="primary" class="ele-btn-icon" icon="el-icon-plus" style="width: 10%;" @click="OpenOutOrderList"  >选择销售出库单</el-button>
            </div>
          </div>
        </div> 
        <ele-pro-table ref="table" :datasource="form.outOrderTable" row-key="id" :need-page="false"  :columns="warehouseItemColumns"   :height="tableHeight" :full-height="tableFullHeight" >
          <template slot="toolbar">
          </template>
          <template slot="billNo" slot-scope="{ row }"  >
            <el-link  type="primary"   @click="clickbillNo(row)" >{{ row.billNo }}</el-link>
          </template>
        </ele-pro-table>
      </el-card>
      <el-card shadow="never"> </el-card>
      <div class="ele-bottom-tool">
          <div class="ele-bottom-tool-actions">
            <el-button type="primary" :loading="loading" @click="save"  v-permission="'Financial_Salecommission_Export'">
              确定
            </el-button>
          <el-button @click="handleClose">关闭</el-button>
          </div>
        </div>
    </el-form>
    <!-- 编辑弹窗 -->
    <salecommissionitemList :data="current" :visible.sync="showEdit"  @callback="reloadOutOrderList"/>
  </div>
</template>
<script>

//初始化对像
import { removePageTab, reloadPageTab,setPageTabTitle } from '@/utils/page-tab-util';
import { GetAllAccount } from '@/api/usermanager/accountmanager';
import { GetAllBackAccount } from '@/api/basicdatamanager/bankaccount';
import { QueryAllChildDictViewByCode } from '@/api/systemmanager/dictmanager';
import { QueryCustomerPageList } from '@/api/basicdatamanager/customer';
import { AddPaysalecommission } from '@/api/finance/salecommission';
import { QuerySaleoutorderByCondition } from '@/api/businesshandling/saleoutmanger';
import { QueryModelByScurrencyId } from '@/api/basicdatamanager/ratemanager';
import salecommissionitemList from '../components/salecommissionitem-list.vue';

export default {
  name: 'SalecommissionDetail',
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object,
  },
  components:{salecommissionitemList},
  data() {
    return {
      // 表单数据
      form: {customerId:'', bankAccountId:'',recDate:new Date(),currencyId:'',rate:0,payAmount:0,payAmountCn:0,outOrderTable:[]},
      fixedHeight:true,
      // 提交状态
      loading: false,
      current:null,
      // 是否是修改
      isUpdate: 1,
      computeDirection:2,//默认奈拉
      showEdit:false,
      //表格选中数据(多选)，如果要回显选中数据可在 done 事件里面使用 setSelectedRowKeys 方法
      currencyDatas:[],
      customerDatas:[],
      bankAccountDatas:[],
      // 表格列配置
      warehouseItemColumns: [
        {columnKey: 'index', type: 'index', width: 50, align: 'center', showOverflowTooltip: true, fixed: 'left', label:'序号',},
        {prop: 'outOrderNo', label: '出库单号', showOverflowTooltip: true, align: 'center',},
        {prop: 'customerName', label: '客户名称',  showOverflowTooltip: true, align: 'center',},
        {prop: 'commissionAmountTotal', label: '提成金额', showOverflowTooltip: true,align: 'center',},
        {prop: 'currencyDesc', label: '币种',showOverflowTooltip: true,align: 'center',},
        {prop: 'commissionAmountCnTotal', label: '提成金额(￥)',   showOverflowTooltip: true, align: 'center',},
        {
          prop: 'createDate', label: '日期', showOverflowTooltip: true, align: 'center',sortable: 'createDate',
          formatter: (row, column, cellValue) => {return this.$util.toDateString(cellValue,"YYYY-MM-DD");}
        },
      ],
      // 表单验证规则
      rules: {
        currencyId:[{required: true,message: '请选择币种',trigger: 'blur'}],
        customerId: [{required: true,message: '请选择客户名称',trigger: 'blur'}],
        payAmount: [{required: true,message: '请输入付款金额',trigger: 'blur'}],
        recDate: [{required: true,message: '请输入付款日期',trigger: 'blur'}],
        bankAccountId: [{required: true,message: '请输入付款账户',trigger: 'blur'}],
      },
    };
  },
  computed: {
      // 表格高度
      tableHeight() {
        var fh = this.fixedHeight ? 'calc(100vh - 450px)' : void 0;
        return fh;
      },
      // 表格全屏时高度
      tableFullHeight() {
        var fh =  this.fixedHeight ? 'calc(100vh - 350px)' : null;
        return fh;
      },
    },
    mounted(){
      this.setDefaultCurreny();
    },
    created(){
      this.initData();
    },
  methods: {

   

    /* 初始化数量 */
    async initData(){

      GetAllAccount().then((data)=>{
        this.operatorDatas = [];
        this.operatorDatas = data;
      });

      GetAllBackAccount().then((data)=>{
        this.bankAccountDatas = [];
        this.bankAccountDatas = data;
      });

      QueryAllChildDictViewByCode(this.Constant.C_HB).then((data)=>{
        this.currencyDatas = [];
        this.currencyDatas = data;
      });

      let params = {
        pageindex: 1,
        pagesize: 100000,
        conditions: [],
        orderBys: [{ sort: "createDate", order: 1, }],
      };

      let result = await QueryCustomerPageList(params);
      this.customerDatas=[];
      this.customerDatas = result.items;

    },

    changeCustomer(val){
      this.form.customerId = val;
    },
    //单击单号
    clickbillNo(row){
      
      removePageTab({ key: '/businesshandling/saleoutmanager' });
      this.$nextTick(() => {
        this.$router.push({path: '/businesshandling/saleoutmanager', query: { "orderNo": row.orderNo } });
      });
    },

    /* 保存编辑 */
    save() {
      //校验必填信息
      this.$refs['form'].validate((valid) => {
        if (!valid) {return false;}

        let pamount = parseFloat(this.form.amount);
        if(pamount<=0){
          this.$message.info("付款金额不能小于零");
          return
        }

        let outOrderId = [];
        this.form.outOrderTable.map((item)=>{
          outOrderId.push(item.id);
        })

        this.form.outOrderList = outOrderId;
      

        this.loading = true;
        AddPaysalecommission(this.form)
          .then((msg) => {
            this.loading = false;
            this.$message.success(msg);
           
            removePageTab({ key: this.$route.path });
            reloadPageTab({ fullPath: '/financialmanager/salecommission' });
          })
          .catch((e) => {
            this.loading = false;
            this.$message.error(e.message);
          });
      });
    },

    /* 选择币种 */
    changeCurrencyRate(val){
      this.$set(this.form,'rate',1);
      QueryModelByScurrencyId(val).then((res)=>{
        if(res){
          this.$set(this.form,'rate',res.rate);
          this.computeDirection = res.computeDirection;
        }
        this.setAmount();
      });
    },

    setAmount(){
      if(this.form.rate && this.form.payAmount){
        this.form.payAmountCn = this.computeDirection == 1?  (this.form.payAmount*this.form.rate).toFixed(4):(this.form.payAmount/this.form.rate).toFixed(4);
      }
    },
    
    //设置币种
    setDefaultCurreny(){
      // C-HB03
      QueryAllChildDictViewByCode(this.Constant.C_HB).then((d)=>{

        d.map((item)=>{
          if(item.code == 'C-HB03'){
          this.form.currencyId = item.id;
          this.changeCurrencyRate(item.id);
        }
        })
      });
    },

    handleClose(){
      removePageTab({ key: this.$route.path });
      reloadPageTab({ fullPath: '/financialmanager/salecommission' });
    },

    /* 刷新表格 */
    reload(where) {
      if(this.$refs.table){
        this.$refs.table.reload({ where: where });
      }
    },

    reloadOutOrderList(items){

      this.form.outOrderTable = items;
      this.form.payAmount = this.form.outOrderTable.reduce((pre,cur)=> { return parseFloat(pre?pre:0)  + parseFloat(cur.commissionAmountTotal?cur.commissionAmountTotal:0)  },0);
      this.form.payAmountCn = this.form.outOrderTable.reduce((pre,cur)=> { return parseFloat(pre?pre:0)  + parseFloat(cur.commissionAmountCnTotal?cur.commissionAmountCnTotal:0)  },0);
    },

    OpenOutOrderList(){
      if(!this.form.customerId || !this.form.currencyId){
        this.$message.info('必须选择客户和币种条件');
        return;
      }

      this.showEdit =true;
      this.current = this.form;
    },

},
  
  /* 监听visible属性变化 */
  watch: {
    visible(visible) {
      if (visible) {
        if (this.data && this.data.id) {
          //赋值this.form
          this.form = this.data;
          this.isUpdate = this.data.id !=null && this.data.id !=undefined;

          this.reload();
        } 
      } 
    }
  }
};
</script>